package org.fire;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.fire.exception.MinaConnectionException;
import org.fire.mina.MinaConnectorHandler;
import org.fire.mina.MinaMessageHandler;
import org.fire.mina.MinaProtocolCodecFactory;

import android.app.Application;
import android.content.Context;

public class FireApplication extends Application {
	public static FireApplication getApplication(Context context) {
		return (FireApplication) context.getApplicationContext();
	}

	private IoSession session;
	private MinaMessageHandler messageHandler;

	public MinaMessageHandler getMessageHandler() {
		return messageHandler;
	}

	public void setMessageHandler(MinaMessageHandler messageHandler) {
		this.messageHandler = messageHandler;
	}

	public void sendMessage(String str) throws MinaConnectionException {
		getMinaSession().write(str);
	}

	public void connectToServer() throws MinaConnectionException {
		doConnectToServer();
	}

	public void doConnectToServer() throws MinaConnectionException {
		try {
			NioSocketConnector connector = new NioSocketConnector();
			connector.getFilterChain().addLast("codec",
					new ProtocolCodecFilter(new MinaProtocolCodecFactory()));

			connector.setConnectTimeoutCheckInterval(30);
			connector.setHandler(new MinaConnectorHandler());

			ConnectFuture cf = connector.connect(new InetSocketAddress(
					"139.196.44.13", 9123));
			// ConnectFuture cf = connector.connect(new InetSocketAddress(
			// "192.168.1.109", 9123));
			cf.awaitUninterruptibly(30000);

			session = cf.getSession();
			session.setAttribute("application", this);

			sendMessage("{\"addr\":\"00000001\", \"action\":\"login\"}");

			startHeartBeat();

		} catch (Exception e) {
			throw new MinaConnectionException(e);
		}
	}

	private void startHeartBeat() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000 * 60);
					} catch (InterruptedException e1) {
					}

					try {
						sendMessage("{\"addr\":\"00000001\", \"action\":\"ping\"}");
					} catch (MinaConnectionException e) {
					}
				}

			}
		}).start();
		;
	}

	private IoSession getMinaSession() throws MinaConnectionException {
		if (!session.isActive()) {
			throw new MinaConnectionException("Invalid connection.");
		}

		return session;
	}
}
